import {
  GoodsModel
} from '../../models/goods.js';

const goodsModel = new GoodsModel();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: 0,
    page: 1,
    size: 10000,
    brotherCategory: [],
    currentCategory: [],
    goodsList: [],
    scrollLeft: 0,
    scrollTop: 0,
    scrollHeight: 0,
    noneResult: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.id) {
      this.setData({
        id: parseInt(options.id)
      });
    }

    wx.getSystemInfo({
      success: (res) => {
        this.setData({
          scrollHeight: res.windowHeight
        });
      }
    });

    this.getCategoryData(this.data.id);
  },
  
  onSwitchCate: function(event) {
    const currentTarget = event.currentTarget;
    if(this.data.id == currentTarget.dataset.id) {
      return
    }
    
    var clientX = event.detail.x;
    if (clientX < 60) {
      this.setData({
        scrollLeft: currentTarget.offsetLeft - 60
      });
    }else if (clientX > 330) {
      this.setData({
        scrollLeft: currentTarget.offsetLeft
      })
    }
      
    this.setData({
      id: currentTarget.dataset.id
    });

    this.getCategoryData(currentTarget.dataset.id);
  },
  
  getCategoryData: function(p_id) {
    wx.showLoading({
      title: '加载中...',
    });

    const p_page = this.data.page;
    const p_size = this.data.size;

    const goodsCategory = goodsModel.getGoodsCategory(p_id);
    const goodsList = goodsModel.getGoodsList(p_id, p_page, p_size);

    Promise.all([goodsCategory, goodsList]).then(res => {
      this.setData({
        brotherCategory: res[0].data.brotherCategory,
        currentCategory: res[0].data.currentCategory,
        goodsList: res[1].data.goodsList
      })

      if(!this.data.goodsList.length) {
        this.setData({
          noneResult: true
        })
      }else {
        this.setData({
          noneResult: false
        })
      }

      wx.hideLoading()
    })
  }
})